import 'package:ble_helper_plugin/library.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class BluetoothAdapterLorin extends BluetoothUuidAdapterBase {
  @override
  String get notifyCharacteristicUuid => '6e400003-b5a3-f393-e0a9-e50e24dcca9e';

  @override
  String get notifyServiceUuid => '6e400001-b5a3-f393-e0a9-e50e24dcca9e';

  @override
  String get writeCharacteristicUuid => '6e400002-b5a3-f393-e0a9-e50e24dcca9e';

  @override
  String get writeServiceUuid => '6e400001-b5a3-f393-e0a9-e50e24dcca9e';
}

class LorinHandlerSettings extends HandlerSettingsBase {
  @override
  bool get supportsConcurrentRequests => true;

  @override
  int get concurrentRequestsMaxLength => 256;

  @override
  List<String> getRequestMsgId(List<int> requestData) {
    return [""];
  }

  @override
  List<String> getResponseMsgId(List<int> responseData) {
    return [""];
  }
}

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final BluetoothConnectHelper _managerHelper =
      BluetoothConnectHelper([BluetoothAdapterLorin()]);

  @override
  void initState() {
    super.initState();

    _managerHelper.bluetoothConnectState.listen((event) {
      switch (event) {
        case CustomBluetoothConnectState.unavailable:
          Fluttertoast.showToast(msg: "不可用");
          break;
        case CustomBluetoothConnectState.idle:
          break;
        case CustomBluetoothConnectState.isScanning:
          break;
        case CustomBluetoothConnectState.connected:
          Fluttertoast.showToast(msg: "连接成功");
          break;
        case CustomBluetoothConnectState.connecting:
          break;
        case CustomBluetoothConnectState.disconnected:
          Fluttertoast.showToast(msg: "连接断开");
          break;
      }
    });
  }

  List<CustomScanResult> scanResults = [];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Bluetooth Plugin Demo'),
        ),
        body: Column(
          children: [
            Expanded(
              child: ListView.builder(
                itemCount: scanResults.length,
                itemBuilder: (context, index) {
                  CustomScanResult result = scanResults[index];
                  return InkWell(
                    onTap: () async {
                      _managerHelper.connect(result.device).whenComplete(() {
                        Fluttertoast.showToast(msg: "连接成功");
                      });
                    },
                    child: ListTile(
                      title: Text(result.advertisementData.advName),
                      subtitle: Text(result.device.remoteId.toString()),
                    ),
                  );
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ElevatedButton(
                    onPressed: () async {
                      await _managerHelper.startScan(
                        callbackScanResults: (devices) {
                          setState(() {
                            debugPrint("【$runtimeType】result: $devices");
                            scanResults = devices;
                          });
                        },
                      );
                    },
                    child: const Text('开始扫描'),
                  ),
                  ElevatedButton(
                    onPressed: () async {
                      await _managerHelper.stopScan();
                    },
                    child: const Text('停止扫描'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
